package com.ruoyi.channel.service.impl;

import com.ruoyi.basedata.domain.PayKind;
import com.ruoyi.basedata.domain.WalletKind;
import com.ruoyi.basedata.mapper.PayKindMapper;
import com.ruoyi.basedata.mapper.WalletKindMapper;
import com.ruoyi.channel.domain.ChannelWallet;
import com.ruoyi.channel.domain.MpChannel;
import com.ruoyi.channel.domain.MpChannelMethod;
import com.ruoyi.channel.mapper.ChannelWalletMapper;
import com.ruoyi.channel.mapper.MpChannelMapper;
import com.ruoyi.channel.mapper.MpChannelMethodMapper;
import com.ruoyi.channel.service.IMpChannelMethodService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.financial.domain.FinancialWallet;
import com.ruoyi.financial.mapper.FinancialWalletMapper;
import com.ruoyi.financial.service.IFinancialWalletService;
import com.ruoyi.merchant.domain.*;
import com.ruoyi.merchant.mapper.MpMerchantMapper;
import com.ruoyi.merchant.mapper.MpMerchantMethodMapper;
import com.ruoyi.merchant.mapper.MpMerchantWalletMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 *  服务层实现
 * 
 * @author ruoyi
 * @date 2019-05-06
 */
@Service
public class MpChannelMethodServiceImpl implements IMpChannelMethodService
{
	/** 渠道支付方法的钱包类型是否唯一的返回结果 */
	public final static String METHOD_WALLET_UNIQUE = "0";
	public final static String METHOD_WALLET_NOT_UNIQUE = "1";


	Logger logger = LoggerFactory.getLogger(MpChannelMethodServiceImpl.class);

	/** 渠道支付方法加返回结果 */
	public final static int METHOD_ADD_SUCCESS = 1;
	public final static int METHOD_ADD_FALSE = -1;

	@Autowired
	private MpChannelMethodMapper mpChannelMethodMapper;
	@Autowired
	private ChannelWalletMapper channelWalletMapper;
	@Autowired
	private MpChannelMapper mpChannelMapper;
	@Autowired
	private PayKindMapper payKindMapper;
	@Autowired
	private WalletKindMapper walletKindMapper;
	@Autowired
	private MpMerchantMethodMapper merchantMethodMapper;
	@Autowired
	private MpMerchantMapper merchantMapper;

	/**
     * 查询信息
     * 
     * @param id ID
     * @return 信息
     */
    @Override
	public MpChannelMethod selectMpChannelMethodById(Long id)
	{
	    return mpChannelMethodMapper.selectMpChannelMethodById(id);
	}
	
	/**
     * 查询列表
     * 
     * @param mpChannelMethod 信息
     * @return 集合
     */
	@Override
	public List<MpChannelMethod> selectMpChannelMethodList(MpChannelMethod mpChannelMethod)
	{
	    return mpChannelMethodMapper.selectMpChannelMethodList(mpChannelMethod);
	}
	
    /**
     * 新增
     * 
     * @param mpChannelMethod 信息
     * @return 结果
     */
	@Override
	public AjaxResult insertMpChannelMethod(MpChannelMethod mpChannelMethod,BigDecimal merchantPayRate)
	{
		// 添加渠道支付方法
		// 查询对应的渠道   设置渠道支付方法的渠道信息
		MpChannel mpChannel = mpChannelMapper.selectMpChannelById(mpChannelMethod.getChannelId().intValue());
		if (StringUtils.isNotNull(mpChannel)) {
			mpChannelMethod.setChannelName(mpChannel.getName());
			mpChannelMethod.setChannelCode(mpChannel.getCode());
			mpChannelMethod.setChannelStatus(mpChannel.getStatus());
			mpChannelMethod.setChannelWithdrawalLevel(mpChannel.getWithdrawalLevel());
			mpChannelMethod.setChannelWithdrawalFee(mpChannel.getWithdrawalFee());
			mpChannelMethod.setChannelMchWithdrawalFee(mpChannel.getMchWithdrawalFee());
			mpChannelMethod.setChannelWithdrawalLimtLeft(mpChannel.getWithdrawalLimtLeft());
			mpChannelMethod.setChannelWithdrawalLimtRight(mpChannel.getWithdrawalLimtRight());
			mpChannelMethod.setChannelClassName(mpChannel.getClassName());
			mpChannelMethod.setChannelReqUrl(mpChannel.getReqUrl());
			mpChannelMethod.setChannelSecretKey(mpChannel.getSecretKey());
			mpChannelMethod.setChannelWithdrawalInner(mpChannel.getWithdrawalInner());
		}
		// 查询对应的支付类型   设置渠道支付方法的支付类型信息
		PayKind payKind = payKindMapper.selectPayKindById(mpChannelMethod.getPayKindId());
		if (StringUtils.isNotNull(payKind)) {
			mpChannelMethod.setPayKindName(payKind.getName());
			mpChannelMethod.setPayKindCode(payKind.getCode());
		}
		// 查询对应的钱包类型  设置渠道支付方法的钱包类型信息
		WalletKind walletKind = walletKindMapper.selectWalletKindById(mpChannelMethod.getWalletKindId().intValue());
		if (StringUtils.isNotNull(walletKind)) {
			mpChannelMethod.setWalletKindName(walletKind.getName());
			mpChannelMethod.setWalletKindCode(walletKind.getCode());
		}
		// 添加渠道支付方法
		mpChannelMethodMapper.insertMpChannelMethod(mpChannelMethod);

		// 拿到刚刚新增的渠道支付方法，为每一个商户添加此方法
		MpChannelMethod existMpChannelMethod = new MpChannelMethod();
		existMpChannelMethod.setChannelId(mpChannelMethod.getChannelId());
		existMpChannelMethod.setPayKindId(mpChannelMethod.getPayKindId());
		List<MpChannelMethod> mpChannelMethodList = mpChannelMethodMapper.selectMpChannelMethodList(existMpChannelMethod);
		if (mpChannelMethodList.size() > 0) {
			addMerchantMethod(mpChannelMethodList.get(0),mpChannel,merchantPayRate);
		}
		return AjaxResult.success("添加成功");
	}



	// 拿到刚刚新增的渠道支付方法，为每一个商户添加此方法
	private void addMerchantMethod(MpChannelMethod channelMethod,MpChannel channel,BigDecimal merchantPayRate) {
		// 查询所有的商户
		// 查询所有商户
		MpMerchant merchant = new MpMerchant();
		List<MpMerchantRSP> merchantRSPList = merchantMapper.selectMpMerchantList(merchant);
		// 要添加的商户支付方法
		List<MpMerchantMethod> insertMerchantMethods = new ArrayList<>();
		if (merchantRSPList.size() > 0) {
			for (MpMerchantRSP mpMerchantRSP : merchantRSPList) {
				MpMerchantMethod merchantMethod = new MpMerchantMethod();
				// 商户支付方法 - 信息
				merchantMethod.setPayRate(merchantPayRate);
				merchantMethod.setLevel(10);
				merchantMethod.setStatus(1);

				// 商户支付方法 - 商户信息
				merchantMethod.setMerchantId(mpMerchantRSP.getId());
				merchantMethod.setMerchantName(mpMerchantRSP.getName());
				merchantMethod.setMerchantCode(mpMerchantRSP.getCode());
				merchantMethod.setMerchantStatus(mpMerchantRSP.getStatus());

				// 商户支付方法 - 渠道支付方法信息
				merchantMethod.setChannelMethodId(channelMethod.getId());
				merchantMethod.setChannelMethodStatus(channelMethod.getStatus());
				merchantMethod.setChannelMethodPayRate(channelMethod.getPayRate());
				merchantMethod.setChannelMethodPayLimitLeft(channelMethod.getPayLimitLeft());
				merchantMethod.setChannelMethodPayLimitRight(channelMethod.getPayLimitRight());

				// 商户支付方法 - 渠道信息
				merchantMethod.setChannelId(channel.getId());
				merchantMethod.setChannelName(channel.getName());
				merchantMethod.setChannelCode(channel.getCode());
				merchantMethod.setChannelStatus(channel.getStatus());
				merchantMethod.setChannelWithdrawalLevel(channel.getWithdrawalLevel());
				merchantMethod.setChannelWithdrawalFee(channel.getWithdrawalFee());
				merchantMethod.setChannelMchWithdrawalFee(channel.getMchWithdrawalFee());
				merchantMethod.setChannelWithdrawalLimtLeft(channel.getWithdrawalLimtLeft());
				merchantMethod.setChannelWithdrawalLimtRight(channel.getWithdrawalLimtRight());
				merchantMethod.setChannelClassName(channel.getClassName());
				merchantMethod.setChannelReqUrl(channel.getReqUrl());
				merchantMethod.setChannelSecretKey(channel.getSecretKey());
				merchantMethod.setChannelWithdrawalInner(channel.getWithdrawalInner());

				// 商户支付方法 - 支付类型信息
				PayKind payKind = payKindMapper.selectPayKindById(channelMethod.getPayKindId());
				merchantMethod.setPayKindId(payKind.getId());
				merchantMethod.setPayKindName(payKind.getName());
				merchantMethod.setPayKindCode(payKind.getCode());

				// 商户支付方法 - 钱包类型信息
				WalletKind walletKind = walletKindMapper.selectWalletKindById(channelMethod.getWalletKindId().intValue());
				merchantMethod.setWalletKindId(walletKind.getId());
				merchantMethod.setWalletKindName(walletKind.getName());
				merchantMethod.setWalletKindCode(walletKind.getCode());

				// 保存
				insertMerchantMethods.add(merchantMethod);
			}
		}
		// 添加商户支付方法
		if (insertMerchantMethods.size() > 0) {
			merchantMethodMapper.insertMerchantMethodList(insertMerchantMethods);
		}
	}




	/**
     * 修改
     * 
     * @param mpChannelMethod 信息
     * @return 结果
     */
	@Override
	public AjaxResult updateMpChannelMethod(MpChannelMethod mpChannelMethod,Long oldPayKindId, Long oldWalletKindId)
	{
		try {
			ChannelWallet channelWalletExist = channelWalletMapper.selectChannelWalletByChannelIdAndWalletKindId(mpChannelMethod.getChannelId(), mpChannelMethod.getWalletKindId());
			if (StringUtils.isNull(channelWalletExist)) {
				// 新增对应渠道钱包
				ChannelWallet channelWallet = new ChannelWallet();
				// 渠道标识
				channelWallet.setChannelId(mpChannelMethod.getChannelId());
				// 余额
				BigDecimal accountBalance = new BigDecimal("0.00");
				channelWallet.setAccountBalance(accountBalance);
				// 待结算金额
				BigDecimal waitLiquidatedBalance = new BigDecimal("0.00");
				channelWallet.setWaitLiquidatedBalance(waitLiquidatedBalance);
				channelWalletMapper.insertChannelWallet(channelWallet);
			}
			// 修改渠道支付方法
			int compare = mpChannelMethod.getPayLimitLeft().compareTo(mpChannelMethod.getPayLimitRight());
			if (compare == 1 ){
				return AjaxResult.error("修改失败！支付限额范围不正确！<br/> 支付限额左 > 支付限额右");
			}else if (compare == 0) {
				return AjaxResult.error("修改失败！支付限额范围不正确！<br/> 支付限额左 = 支付限额右");
			}
			// 查看是否有商户添加该渠道支付方法，修改渠道支付方法的费率不能大于商户支付方法的费率
			MpMerchantMethod merchantMethod = new MpMerchantMethod();
			merchantMethod.setChannelMethodId(mpChannelMethod.getId());
			List<MpMerchantMethod> merchantMethodList = merchantMethodMapper.selectMpMerchantMethodList(merchantMethod);
			if (merchantMethodList.size() > 0) {
				for (MpMerchantMethod mpMerchantMethodExist : merchantMethodList) {
					int flag = mpMerchantMethodExist.getPayRate().compareTo(mpChannelMethod.getPayRate());
					if (flag == -1 || flag == 0) {
						return AjaxResult.error("修改失败！已有商家添加该渠道支付方法，商家的支付费率要大于渠道的支付费率！");
					}else {
						// 更新商户支付方法的渠道支付方法信息
						mpMerchantMethodExist.setChannelMethodStatus(mpChannelMethod.getStatus());
						mpMerchantMethodExist.setChannelMethodPayRate(mpChannelMethod.getPayRate());
						mpMerchantMethodExist.setChannelMethodPayLimitLeft(mpChannelMethod.getPayLimitLeft());
						mpMerchantMethodExist.setChannelMethodPayLimitRight(mpChannelMethod.getPayLimitRight());
						// 更新商户支付方法
						merchantMethodMapper.updateMpMerchantMethod(mpMerchantMethodExist);
					}
				}
			}
            /*===========================更新渠道支付方法，同时更新商户支付方法相关信息===========================*/
            // 查询对应的支付类型   设置渠道支付方法的支付类型信息
            PayKind payKind = payKindMapper.selectPayKindById(mpChannelMethod.getPayKindId());
            if (StringUtils.isNotNull(payKind)) {
                mpChannelMethod.setPayKindName(payKind.getName());
                mpChannelMethod.setPayKindCode(payKind.getCode());

                // 更新商户支付方法的支付类型信息
                MpMerchantMethod merchantMethodPayKind = new MpMerchantMethod();
				merchantMethodPayKind.setPayKindId(oldPayKindId);
				merchantMethodPayKind.setChannelMethodId(mpChannelMethod.getId());
                List<MpMerchantMethod> merchantMethodPayKindList = merchantMethodMapper.selectMpMerchantMethodList(merchantMethodPayKind);
                for (MpMerchantMethod merchantMethodPayKindUpdate : merchantMethodPayKindList) {
					merchantMethodPayKindUpdate.setPayKindId(payKind.getId());
                    merchantMethodPayKindUpdate.setPayKindName(payKind.getName());
                    merchantMethodPayKindUpdate.setPayKindCode(payKind.getCode());
                    // 更新
                    merchantMethodMapper.updateMpMerchantMethod(merchantMethodPayKindUpdate);
                }
            }
            // 查询对应的钱包类型  设置渠道支付方法的钱包类型信息
            WalletKind walletKind = walletKindMapper.selectWalletKindById(mpChannelMethod.getWalletKindId().intValue());
            if (StringUtils.isNotNull(walletKind)) {
                mpChannelMethod.setWalletKindName(walletKind.getName());
                mpChannelMethod.setWalletKindCode(walletKind.getCode());

                // 更新商户支付方法的钱包类型信息
                MpMerchantMethod merchantMethodWalletKind = new MpMerchantMethod();
				merchantMethodWalletKind.setChannelMethodId(mpChannelMethod.getId());
                merchantMethodWalletKind.setWalletKindId(oldWalletKindId);
                List<MpMerchantMethod> merchantMethodWalletKindList = merchantMethodMapper.selectMpMerchantMethodList(merchantMethodWalletKind);
                for (MpMerchantMethod merchantMethodWalletKindUpdate : merchantMethodWalletKindList) {
                    merchantMethodWalletKindUpdate.setWalletKindId(walletKind.getId());
                    merchantMethodWalletKindUpdate.setWalletKindName(walletKind.getName());
                    merchantMethodWalletKindUpdate.setWalletKindCode(walletKind.getCode());
					// 更新商户支付方法的钱包类型信息
                    merchantMethodMapper.updateMpMerchantMethod(merchantMethodWalletKindUpdate);
                }
            }
			mpChannelMethodMapper.updateMpChannelMethod(mpChannelMethod);
			return AjaxResult.success("修改成功");
		} catch (Exception e) {
			logger.error("修改渠道支付方法异常！",e);
			return AjaxResult.error("修改失败");
		}
	}

	/**
     * 删除对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteMpChannelMethodByIds(String ids)
	{
		return mpChannelMethodMapper.deleteMpChannelMethodByIds(Convert.toStrArray(ids));
	}


    /**
     * 渠道支付方法状态修改
     *
     * @param mpChannelMethod 渠道支付方法
     * @return                结果
     */
    @Override
    public int changeStatus(MpChannelMethod mpChannelMethod) {
    	// 同时更新商户支付方法的渠道支付方法状态
		MpMerchantMethod merchantMethod = new MpMerchantMethod();
		merchantMethod.setChannelMethodId(mpChannelMethod.getId());
		List<MpMerchantMethod> merchantMethodListExist = merchantMethodMapper.selectMpMerchantMethodList(merchantMethod);
		if (merchantMethodListExist.size() > 0) {
			for (MpMerchantMethod merchantMethodExist : merchantMethodListExist) {
				merchantMethodExist.setChannelMethodStatus(mpChannelMethod.getStatus());
				//更新
				merchantMethodMapper.updateMpMerchantMethod(merchantMethodExist);
			}
		}
		return mpChannelMethodMapper.updateMpChannelMethod(mpChannelMethod);
    }


	/**
	 * 校验渠道支付方法的钱包类型
	 *
	 * @param id
	 * @param channelId
	 * @param walletKindId
	 * @return
	 */
	@Override
	public String checkWalletKindIdUnique(Long id, Long channelId, Long walletKindId) {
		MpChannelMethod info = mpChannelMethodMapper.checkWalletKindIdUnique(channelId,walletKindId);
		if (StringUtils.isNotNull(info) && info.getId() != id){
			return METHOD_WALLET_NOT_UNIQUE;
		}
		return METHOD_WALLET_UNIQUE;
	}


	/**
	 * 拿到最大支付费率
	 */
	@Override
	public BigDecimal maxPayRate() {
		return mpChannelMethodMapper.maxPayRate();
	}


	/**
	 * 根据渠道id 拿到最大支付费率
	 *
	 * @param channelId
	 * @return
	 */
	@Override
	public BigDecimal maxPayRateByChannelId(int channelId) {
		return mpChannelMethodMapper.maxPayRateByChannelId(channelId);
	}
}
